package org.example.route.handler;


import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.util.StopWatch;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

//TODO 用于处理通用的表格数据
//可以用于继承
public abstract class ExcelHandler {


    protected void assembleData(XSSFWorkbook workbook, List<?> data,String prop){}


    //下载文件
    public void fileDownload(List<?> data, String prop,HttpServletResponse  response) {

        StopWatch stopWatch = new StopWatch("数据分析表下载...");
        stopWatch.start("开始组装模板");


        // 使用 RFC 6266 规范编码中文文件名
        String encodedFileName = null;
        encodedFileName = URLEncoder.encode(prop, StandardCharsets.UTF_8);

        ServletOutputStream out = null;

        try {
            // 设置响应头，确保浏览器正确处理下载
//            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//            response.setHeader("Content-Disposition", "attachment;filename=filename.xlsx");
//            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//            response.setCharacterEncoding("utf-8");
//            response.addHeader("Content-Disposition", "attachment;filename*=UTF-8''" + URLEncoder.encode(filename, "UTF-8"));

            // 设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + encodedFileName);
            out = response.getOutputStream();
        } catch (Exception ex) {
            // 错误处理（假设EasyLogger和LogLevel已定义）
            // EasyLogger.logger(this.getClass().getSimpleName(), ThrowableConvert.throwableResult(ex), LogLevel.ERROR);
            ex.printStackTrace();
            return;
        }

        XSSFWorkbook workbook = new XSSFWorkbook();
        assembleData(workbook, data, prop);

        try {
            workbook.write(out);
            out.flush();
        } catch (IOException ex) {
            // 错误处理（假设EasyLogger和LogLevel已定义）
            // EasyLogger.logger(this.getClass().getSimpleName(), ThrowableConvert.throwableResult(ex), LogLevel.ERROR);
            ex.printStackTrace();
        } finally {
            try {
                if (workbook != null) {
                    workbook.close();
                }
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        stopWatch.stop();
    }

}
